package MicroSpring.beanPostProcessor.metadata;


import MicroSpring.beanFactory.impl.DefaultListableBeanFactory;
import MicroSpring.common.StringUtils;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Collection;

public class InjectionMetadata {
    //final处理
    private Class<?> targetClass;
    private Collection<InjectedElement> injectedElements;
    private final DefaultListableBeanFactory beanFactory;

    public InjectionMetadata(DefaultListableBeanFactory beanFactory) {
        this.beanFactory = beanFactory;
    }

    public Class<?> getTargetClass() {
        return targetClass;
    }

    public void setTargetClass(Class<?> targetClass) {
        this.targetClass = targetClass;
    }

    public Collection<InjectedElement> getInjectedElements() {
        return injectedElements;
    }

    public void setInjectedElements(Collection<InjectedElement> injectedElements) {
        this.injectedElements = injectedElements;
    }

    /*
            将injectedElements注入到目标bean中
         */
    public void inject(Object target,  String beanName) throws IllegalAccessException {
        for (InjectedElement injectedElement : injectedElements) {
            Field field = injectedElement.getField();
            field.setAccessible(true);
            Class injectClazz = injectedElement.getInjectClazz();
            if (injectClazz==null&&StringUtils.hasText(injectedElement.getVals())){
                field.set(target,injectedElement.getVals());
            }
            if (injectClazz !=null && beanFactory.containsBean(injectClazz)){
                //查找这个clazz在容器中是否存在
                //存在，则注入这个bean
                Object injdectBean = beanFactory.getBean(injectClazz);
                field.set(target,injdectBean);
            }

        }
    }


    /*
        静态内部类   放的是那些 /变量/方法参数/
     */
    public static class InjectedElement{
        private String vals;
        private Class injectClazz;
        private Field field;
        private Method method;

        public String getVals() {
            return vals;
        }

        public void setVals(String vals) {
            this.vals = vals;
        }

        public Class getInjectClazz() {
            return injectClazz;
        }

        public void setInjectClazz(Class injectClazz) {
            this.injectClazz = injectClazz;
        }

        public Field getField() {
            return field;
        }

        public void setField(Field field) {
            this.field = field;
        }

        public Method getMethod() {
            return method;
        }

        public void setMethod(Method method) {
            this.method = method;
        }
    }
}
